var $ = require('jquery');
var util = require('../../utils/index');
var api = require('../api');
var queue = [];

/**
 * 将回调函数绑定到上传按钮
 * @param {Element} uploadBtn
 * @param {Function} callback callback(base64, ext)
 */
module.exports.bind = function (uploadBtn, callback) {
  queue.push([uploadBtn, callback]);
  bindAll();
};

function bindAll() {

  var pair = queue.shift();

  if (!pair) {
    return;
  }

  var $btn = $(pair[0]);
  var callback = pair[1];

  var fileInput = $btn.find('.upload-file')[0];
  var $form = $btn.find('form');
  fileInput.onchange = function () {
    if (!this.value) {
      return;
    }
    var arr = this.value.split('.');
    var ext = arr[arr.length - 1];
    var filename = util.createRandomId() + '.' + ext;
    console.log('开始上传图片', filename);
    api.getOssConfig().then(function (conf) {
      console.log('获取OSS配置文件', conf);
      $form.attr('action', conf.url);
      $form.find('input[name="key"]').val(conf.dir + filename);
      $form.find('input[name="policy"]').val(conf.policy);
      $form.find('input[name="OSSAccessKeyId"]').val(conf.accessKeyId);
      $form.find('input[name="success_action_status"]').val('200');
      $form.find('input[name="signature"]').val(conf.signature);
      $form.ajaxForm({
        success: function (data) {
          console.log('上传成功', data);
          callback(conf.url + '/' + conf.dir + filename);
        }
      });
      $form.submit();
      fileInput.value = '';
    });
  };

  bindAll();
}
